package com.zl.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.zl.entity.Agency;
import com.zl.entity.Collect;
import com.zl.entity.NewsEntity;
import com.zl.service.CollectService;
import com.zl.weixin.entity.UserClient;

/**   
* @Title: CollectController.java 
* @Package com.zl.controller 
* @Description: 收藏
* @author chxl   
* @date 2015年8月20日 下午2:03:07 
* @version V1.0   
*/
@Controller
@RequestMapping("collect")
@Scope("prototype")
public class CollectController {
	@Autowired
	private CollectService collectService;
	/**
	 * @return
	 */
	@RequestMapping("newslist")
	public String newslist(Model model,HttpServletRequest request){
		UserClient user = (UserClient)request.getSession().getAttribute("user");
//		UserClient user = new UserClient();
//		user.setOpenid("oFOgks6AbGnBns_u2teOtiMG711c");
		List<NewsEntity> list = collectService.getCollectNews(user.getOpenid());
		model.addAttribute("list", list);//  新闻列表
		return "uc_favor_zb";
	}
	
	@RequestMapping("agencylist")
	public String agencylist(Model model,HttpServletRequest request){
		UserClient user = (UserClient)request.getSession().getAttribute("user");
//		UserClient user = new UserClient();
//		user.setOpenid("oFOgks6AbGnBns_u2teOtiMG711c");
		List<Agency> list = collectService.getCollectAgency(user.getOpenid());
		model.addAttribute("list", list);//  新闻列表
		return "uc_favor_jg";
	}
	
	@ResponseBody
	@RequestMapping("/insert")
	public String insert(Model model,HttpServletRequest request){
		String type = request.getParameter("type");
		String id = request.getParameter("id");
		UserClient user = (UserClient)request.getSession().getAttribute("user");
		//UserClient user = new UserClient();
		//user.setOpenid("oFOgks6AbGnBns_u2teOtiMG711c");
		Map<String,String> result = new HashMap<String,String>();
		List<Collect> list =  collectService.isExist(user.getOpenid(), id);
		if(list==null||list.size()==0){
			Collect collect = new Collect();
			collect.setId(UUID.randomUUID().toString());
			collect.setUserId(user.getOpenid());
			collect.setCollectId(id);
			collect.setType(type);
			collectService.addCollect(collect);
			result.put("message", "收藏成功");
		}else{
			Collect collect = list.get(0);
			collectService.cancelCollect(collect.getId());
			result.put("message", "取消成功");
		}
		
		return JSON.toJSONString(result);
	}
}
